package and.process;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import and.activity.R;
import and.bean.BaseBean;
import and.bean.QueryInfoBean;
import and.common.MyCommon;
import and.tools.FileHelper;

public class QueryProcess {
	private List<BaseBean> result = new ArrayList<BaseBean>();
	private SaveProcess saveProcess =new SaveProcess();
	/*
	 * 查找的主方法
	 */
	public List<BaseBean> query() throws Exception {
		QueryInfoBean bean =new QueryInfoBean();
     	bean.setLength(MyCommon.QueryLength);
     	bean.setName(MyCommon.QueryName);
     	bean.setUrl(MyCommon.QueryFromUrl);
     	bean.setType(MyCommon.QueryType);
     	
		if (!hasNewData()) {
			MyCommon.isNew = false;
			System.out.println("获取文件数据...");
			return queryFromFile();
		} else {
			System.out.println("获取新数据...");
			MyCommon.isNew = true;
		}
		URL url = null;
		result = new ArrayList<BaseBean>();
		BaseBean base = new BaseBean();
		String line = "";
		String dataStr = "";
		String numStr = "";
		String[] datas;
		String[] tempDatas;
		StringBuilder sb = new StringBuilder();
		url = new URL(bean.getUrl());
		InputStream input = url.openStream();
		BufferedReader read = new BufferedReader(new InputStreamReader(input));
		while ((line = read.readLine()) != null) {
			sb.append(line.trim());
		}
		if (MyCommon.FUCAI.equals(bean.getType())) {
			datas = sb.toString().split("<tr>");
			int stratIndex = datas.length - 21;
			for (int i = stratIndex; i < datas.length - 1; i++) {
				dataStr = datas[i];
				tempDatas = dataStr.split("</td>");
				base = new BaseBean();
				base.setName(bean.getName());
				base.setDate(tempDatas[0].split(">")[1]);
				base.setQishu(tempDatas[1].split(">")[1]);
				numStr = createFucaiNum(tempDatas[2].split("</em>"), bean
						.getLength());
				base.setNum(numStr);
				result.add(base);
			}
		} else if (MyCommon.TICAI.equals(bean.getType())) {
			String[] temp;
			datas = sb.toString().toLowerCase().split(
					"<tr align=\"center\" bgcolor=\"#ffffff\">");
			for (int i = 1; i < datas.length; i++) {
				dataStr = datas[i];
				tempDatas = dataStr.split("</td>");
				base = new BaseBean();
				base.setName(bean.getName());
				base.setQishu(tempDatas[0].split(">")[1]);
				temp = dataStr.split("</td></tr>")[0].split(">");
				base.setDate(temp[temp.length - 1]);
				numStr = createTicaiNum(tempDatas);
				base.setNum(numStr);
				result.add(base);
				tempDatas = dataStr.split("</td></tr>")[1].split("</td>");
				base = new BaseBean();
				base.setName(bean.getName());
				temp = tempDatas[0].split(">");
				base.setQishu(temp[temp.length - 1]);
				temp = dataStr.split("</td></tr>")[1].split(">");
				base.setDate(temp[temp.length - 1]);
				numStr = createTicaiNum(tempDatas);
				base.setNum(numStr);
				result.add(base);
			}
		}else if(MyCommon.DFGUANGDONG.equals(bean.getType())){ 
			Pattern pattern1 =Pattern.compile("(?<=<td align=\"center\" bgcolor=\"#ffffff\">)\\d{7}(?=</td>)");
			Matcher matcher1=pattern1.matcher(sb.toString().toLowerCase());
			Pattern pattern2 =Pattern.compile("(?<=luckyno=\")\\d{"+MyCommon.QueryLength*2+"}(?=\">)");
			Matcher matcher2=pattern2.matcher(sb.toString().toLowerCase());
			Pattern pattern3 =Pattern.compile("(?<=<td align=\"center\" bgcolor=\"#faf8e9\">)\\d{7}(?=</td>)");
			Matcher matcher3=pattern3.matcher(sb.toString().toLowerCase());
			int now = 0;
			while(matcher1.find() && matcher2.find()){
				
				now++;
				if(now%2==0){
					now++;
					matcher3.find();
					base = createGDBase(matcher3,matcher2,bean.getName());
					matcher2.find();
					result.add(base);
				}
				base = createGDBase(matcher1,matcher2,bean.getName());
				result.add(base);
			}
			matcher3.find();
			matcher2.find();
			base = createGDBase(matcher3,matcher2,bean.getName());
			result.add(base);
		}
		if(MyCommon.isNew){
     		saveProcess.saveBaseBeanFile(result);
     	}
		return result;
	}
	/*
	 * 创建广东彩票的基础信息
	 */
	private BaseBean createGDBase(Matcher matcherQishu,Matcher matcherNum,String name){
		BaseBean base = new BaseBean();
		StringBuilder numSb = new StringBuilder();
		String qishu=matcherQishu.group();
		base.setQishu(qishu);
		base.setName(name);
		int days =0;
		if(MyCommon.QueryName.equals(MyCommon.GD36XUAN7)){
			days =Integer.parseInt(qishu.substring(4))+7;
		}else if(MyCommon.QueryName.equals(MyCommon.GD26XUAN5)){
			days =Integer.parseInt(qishu.substring(4));
			if(days%3==0){
				days = (days/3)*7+6;
			}else if(days%3==2){
				days =(days/3)*7+11;
			}else if(days%3==1){
				days = (days/3)*7+9;
			}
		}
		
		Calendar c =Calendar.getInstance();
		c.set(Integer.parseInt(qishu.substring(0,4)),0, days);
		Date date= c.getTime();
		SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");
		String time=df.format(date);
		System.out.println(time);
		
		base.setDate(time);
		numSb.append(matcherNum.group());
		for(int i=0;i<MyCommon.QueryLength-1;i++){
			numSb.insert(i*3+2," ");
		}
		base.setNum(numSb.toString());
		return base;
	}
	/*
	 * 从文件里读取数据
	 */
	private List<BaseBean> queryFromFile() throws Exception {
		List<BaseBean> result = new ArrayList<BaseBean>();
		BaseBean bean = new BaseBean();
		String[] datas = FileHelper.read(MyCommon.FILEPATH + MyCommon.SAVEFILENAME,
				"utf-8").split("\n");
		String[] tempDatas;
		for (int i = 0; i < datas.length; i++) {
			bean = new BaseBean();
			tempDatas = datas[i].split(";");
			bean.setName(tempDatas[0]);
			bean.setQishu(tempDatas[1]);
			bean.setDate(tempDatas[2]);
			bean.setNum(tempDatas[3]);
			result.add(bean);
		}
		return result;
	}
	
	/*
	 * 初始化查询
	 */
	public void initQuery(String selectName){
		if(selectName.equals(MyCommon.FCSHUANGSEQIU)){
			MyCommon.QueryType = MyCommon.FUCAI;
			MyCommon.QueryFromUrl = MyCommon.FCSSQFROMURL;
			MyCommon.QueryLength = 7;
			MyCommon.QueryName = MyCommon.FCSHUANGSEQIU;
			MyCommon.QueryLayoutId =R.layout.queryssq;
			MyCommon.CPTime = "21:30";
			MyCommon.QueryMaxNum = 33;
			MyCommon.SAVEFILENAME =MyCommon.FCSSQFILENAME;
			MyCommon.StatisticsFile = MyCommon.FCSSQFILENAME;
			MyCommon.QueryMinNum = 1;
		}
		if(selectName.equals(MyCommon.FC3D)){
			MyCommon.QueryType = MyCommon.FUCAI;
			MyCommon.QueryFromUrl = MyCommon.FC3DFROMURL;
			MyCommon.QueryLength = 3;
			MyCommon.QueryName = MyCommon.FC3D;
			MyCommon.QueryLayoutId =R.layout.query3d;
			MyCommon.CPTime = "20:30";
			MyCommon.QueryMaxNum = 9;
			MyCommon.SAVEFILENAME = MyCommon.FC3DFILENAME;
			MyCommon.StatisticsFile = MyCommon.FC3DFILENAME;
			MyCommon.QueryMinNum = 0;
		}

		if(selectName.equals(MyCommon.FCQICAILE)){
			MyCommon.QueryType = MyCommon.FUCAI;
			MyCommon.QueryFromUrl = MyCommon.FCQCLFROMURL;
			MyCommon.QueryLength = 8;
			MyCommon.QueryName = MyCommon.FCQICAILE;
			MyCommon.QueryLayoutId =R.layout.queryqcl;
			MyCommon.CPTime = "21:30";
			MyCommon.QueryMaxNum = 31;
			MyCommon.SAVEFILENAME = MyCommon.FCQCLFILENAME;
			MyCommon.StatisticsFile = MyCommon.FCQCLFILENAME;
			MyCommon.QueryMinNum = 1;
		}

		if(selectName.equals(MyCommon.TCDALETOU)){
			MyCommon.QueryType = MyCommon.TICAI;
			MyCommon.QueryFromUrl = MyCommon.TCDLTFROMURL;
			MyCommon.QueryLength = 7;
			MyCommon.QueryName = MyCommon.TCDALETOU;
			MyCommon.QueryLayoutId =R.layout.querydlt;
			MyCommon.CPTime = "20:30";
			MyCommon.QueryMaxNum = 35;
			MyCommon.SAVEFILENAME = MyCommon.TCDLTFILENAME;
			MyCommon.StatisticsFile = MyCommon.TCDLTFILENAME;
			MyCommon.QueryMinNum = 1;
		}

		if(selectName.equals(MyCommon.TCPAILIESAN)){
			MyCommon.QueryType = MyCommon.TICAI;
			MyCommon.QueryFromUrl = MyCommon.TCPLSFROMURL;
			MyCommon.QueryLength = 3;
			MyCommon.QueryName = MyCommon.TCPAILIESAN;
			MyCommon.QueryLayoutId =R.layout.querypl3;
			MyCommon.CPTime = "20:30";
			MyCommon.QueryMaxNum = 9;
			MyCommon.SAVEFILENAME = MyCommon.TCPLSFILENAME;
			MyCommon.StatisticsFile = MyCommon.TCPLSFILENAME;
			MyCommon.QueryMinNum = 0;
		}

		if(selectName.equals(MyCommon.TCPAILIEWU)){
			MyCommon.QueryType = MyCommon.TICAI;
			MyCommon.QueryFromUrl = MyCommon.TCPLWFROMURL;
			MyCommon.QueryLength = 5;
			MyCommon.QueryName = MyCommon.TCPAILIEWU;
			MyCommon.QueryLayoutId =R.layout.querypl5;
			MyCommon.CPTime = "20:30";
			MyCommon.QueryMaxNum = 9;
			MyCommon.SAVEFILENAME = MyCommon.TCPLWFILENAME;
			MyCommon.StatisticsFile = MyCommon.TCPLWFILENAME;
			MyCommon.QueryMinNum = 0;
		}

		if(selectName.equals(MyCommon.TC22XUAN5)){
			MyCommon.QueryType = MyCommon.TICAI;
			MyCommon.QueryFromUrl = MyCommon.TC22XWFROMURL;
			MyCommon.QueryLength = 5;
			MyCommon.QueryName = MyCommon.TC22XUAN5;
			MyCommon.QueryLayoutId =R.layout.query22x5;
			MyCommon.CPTime = "20:30";
			MyCommon.QueryMaxNum = 23;
			MyCommon.SAVEFILENAME = MyCommon.TC22XWFILENAME;
			MyCommon.StatisticsFile = MyCommon.TC22XWFILENAME;
			MyCommon.QueryMinNum = 1;
		}

		if(selectName.equals(MyCommon.TCQIXINGCAI)){
			MyCommon.QueryType = MyCommon.TICAI;
			MyCommon.QueryFromUrl = MyCommon.TCQXCFROMURL;
			MyCommon.QueryLength = 7;
			MyCommon.QueryName = MyCommon.TCQIXINGCAI;
			MyCommon.QueryLayoutId =R.layout.queryqcx;
			MyCommon.CPTime = "20:30";
			MyCommon.QueryMaxNum = 9;
			MyCommon.SAVEFILENAME = MyCommon.TCQXCFILENAME;
			MyCommon.StatisticsFile = MyCommon.TCQXCFILENAME;
			MyCommon.QueryMinNum = 0;
		}
		
		if(selectName.equals(MyCommon.GD36XUAN7)){
			MyCommon.QueryType = MyCommon.DFGUANGDONG;
			MyCommon.QueryFromUrl = MyCommon.GD36XUAN7FROMURL;
			MyCommon.QueryLength = 7;
			MyCommon.QueryName = MyCommon.GD36XUAN7;
			MyCommon.QueryLayoutId =R.layout.querygd36x7;
			MyCommon.CPTime = "21:54";
			MyCommon.QueryMaxNum = 36;
			MyCommon.SAVEFILENAME = MyCommon.DFGD36X7FILENAME;
			MyCommon.StatisticsFile = MyCommon.DFGD36X7FILENAME;
			MyCommon.QueryMinNum = 1;
		}
		
		if(selectName.equals(MyCommon.GD26XUAN5)){
			MyCommon.QueryType = MyCommon.DFGUANGDONG;
			MyCommon.QueryFromUrl = MyCommon.GD26XUAN5FROMURL;
			MyCommon.QueryLength = 5;
			MyCommon.QueryName = MyCommon.GD26XUAN5;
			MyCommon.QueryLayoutId =R.layout.querygd26x5;
			MyCommon.CPTime = "21:54";
			MyCommon.QueryMaxNum = 26;
			MyCommon.SAVEFILENAME = MyCommon.DFGD26X5FILENAME;
			MyCommon.StatisticsFile = MyCommon.DFGD26X5FILENAME;
			MyCommon.QueryMinNum = 1;
		}
	}
	/*
	 * 判断是否有新数据
	 */
	public boolean hasNewData() throws Exception {
		if (!FileHelper.isFileExist(MyCommon.FILEPATH + MyCommon.SAVEFILENAME)) {
			System.out.println("没有找到文件");
			return true;
		}
		String result = FileHelper.readFirstLine(MyCommon.FILEPATH
				+ MyCommon.SAVEFILENAME, "utf-8");
		String lastDate = result.split(";")[2] + " " + MyCommon.CPTime;
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

		Date last = format.parse(lastDate);
		Date now = new Date();
		Date openDate = new Date();
		long milliseconds = now.getTime() -  last.getTime();
		long days = milliseconds / (long) (1000 * 60 * 60 * 24);
		if (days == 0) {
			return false;
		} else if (days > 0
				&& (MyCommon.QueryName.equals(MyCommon.FC3D)
						|| MyCommon.QueryName.equals(MyCommon.TCPAILIESAN)
						|| MyCommon.QueryName.equals(MyCommon.TCPAILIEWU) || MyCommon.QueryName
						.equals(MyCommon.TC22XUAN5) ||  MyCommon.QueryName.equals(MyCommon.GD36XUAN7))) {
			//每天开奖
			if (days == 1) {
				openDate.setHours(21);
				openDate.setMinutes(0);
				return now.after(openDate);
			} else {
				return true;
			}
		} else if (days > 0 && MyCommon.QueryName.equals(MyCommon.TCDALETOU)) {//每周1，3，6开奖
			return isTime(days, 6, now, openDate, 21);
		} else if (days > 0 && MyCommon.QueryName.equals(MyCommon.TCQIXINGCAI)) {//每周2，5，7开奖
			return isTime(days, 5, now, openDate, 21);
		} else if (days > 0
				&& MyCommon.QueryName.equals(MyCommon.FCSHUANGSEQIU) || MyCommon.QueryName.equals(MyCommon.GD26XUAN5) ) {//每周2，4，7开奖
			return isTime(days, 0, now, openDate, 22);
		} else if (days > 0 && MyCommon.QueryName.equals(MyCommon.FCQICAILE)) {//每周1，3，5开奖
			return isTime(days, 1, now, openDate, 22);
		}

		return false;
	}

	/*
	 * 判断是否到时间取数据了
	 */
	private boolean isTime(long days, int longDays, Date now, Date openDate,
			int time) {
		int temp = longDays - 1 > 0 ? longDays - 1 : 6;
		System.out.println("temp:==="+temp);
		if (days > 3) {
			return true;
		} else if (days == 3) {
			if (now.getDay() != longDays) {
				return true;
			} else {
				openDate.setHours(time);
				openDate.setMinutes(0);
				return now.after(openDate);
			}
		} else if (days == 2) {
			if (now.getDay() == temp) {
				return false;
			} else {
				openDate.setHours(time);
				openDate.setMinutes(0);
				return now.after(openDate);
			}
		} else {
			return false;
		}
	}

	/*
	 * 创建福彩号码
	 */
	private String createFucaiNum(String[] datas, int length) {
		String result = "";
		String[] temp;
		for (int i = 0; i < length; i++) {
			temp = datas[i].split(">");
			result += temp[temp.length - 1] + " ";
		}
		return result;
	}

	/*
	 * 创建体彩号码
	 */
	private String createTicaiNum(String[] datas) {
		String data = datas[1].replace("\"","'").split("<font class='fontred'>")[1].replace(
				"</font>", "").replace("<font class='fontblue'>", "").replace("</b>","").replace("<b>","");
		String result = data.replace("+","").replace("&nbsp;", " ").replace("  "," ").replace("  "," ");
		return result;
	}
}
